/**
 * @Author: lll
 * @Email:li.lele@vpclub.cn
 * @Date: create in 2020/7/20
 */
package cn.vpclub.admin.web.home;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/test/webSocket/{sid}")
@Component
public class TestWebSocketServerController {
    Logger log = LoggerFactory.getLogger(TestWebSocketServerController.class);
    private static AtomicInteger onlineNum = new AtomicInteger();
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


    /**
     * 成功建立连接
     *
     * @param session
     * @param userName
     */
    @OnOpen
    public void openCollection(Session session, @PathParam(value = "sid") String userName) {
//        log.info("获取userid  {}", httpServletRequest.getAttribute("userId"));
        log.info("sessionId {}", session.getId());
        sessionPools.put(userName, session);
        addOnlineCount();
        log.info("用户 【【{}】】 加入了webSocket，当前webSocket总人数为【【{}】】", userName, onlineNum);
    }

    /**
     * 接收客户端消息
     *
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void acceptMessage(String message) throws IOException {
        log.info("开始接收管理员消息  {}", message);
        message = "客户端：" + message + ",已收到";
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 推送消息
     *
     * @param session
     * @param message
     * @throws IOException
     */
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 推送消息给指定的用户
     *
     * @param userName
     * @param message
     */
    public void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接断开
     *
     * @param userName
     */
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
        System.out.println(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }


    /**
     * 连接错误
     *
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}
